﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using TomNet.AspNetCore.Mvc;
using TomNet.Core;
using TomNet.Core.Options;

namespace TomNet.App.Web.Common
{
	public class APIController: ApiController
	{
		#region private TokenValidationParameters ValidationParameters

		private TokenValidationParameters ValidationParameters
		{
			get
			{
				if (_validationparameters == null)
				{
					TomNetOptions options = HttpContext.RequestServices.GetTomNetOptions();
					JwtOptions jwtOptions = options.Jwt;

					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					var symmetricKey = System.Text.Encoding.ASCII.GetBytes(jwtOptions.Secret);
					var validationParameters = new TokenValidationParameters()
					{
						RequireExpirationTime = true, //token是否包含有效期
						ValidateIssuer = false, //验证秘钥发行人，如果要验证在这里指定发行人字符串即可
						ValidateAudience = false, //验证秘钥的接受人，如果要验证在这里提供接收人字符串即可
						IssuerSigningKey = new SymmetricSecurityKey(symmetricKey) //生成token时的安全秘钥
					};

					_validationparameters = validationParameters;
				}

				return _validationparameters;
			}
		}
		static TokenValidationParameters _validationparameters = null;

		#endregion

		#region int LoginUserId 登录用户Id。

		/// <summary>
		/// 登录用户Id。
		/// </summary>
		public int LoginUserId
		{
			get
			{
				int result = 0;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					string data = identity.FindFirst(ClaimTypes.NameIdentifier)?.Value;
					int.TryParse(data, out result);
				}

				return result;
			}
		}

		#endregion

		#region string LoginName 登录用户的登录账号。

		/// <summary>
		/// 登录用户的登录账号。
		/// </summary>
		public string LoginName
		{
			get
			{
				string result = string.Empty;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					result = identity.FindFirst("LoginName")?.Value;
				}

				return result;
			}
		}

		#endregion

		#region string LoginUserName 登录用户名称。

		/// <summary>
		/// 登录用户名称。
		/// </summary>
		public string LoginUserName
		{
			get
			{
				string result = string.Empty;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					result = identity.FindFirst(ClaimTypes.Name)?.Value;
				}

				return result;
			}
		}

		#endregion

		#region int LoginRoleId 登录用户角色Id。

		/// <summary>
		/// 登录用户角色Id。
		/// </summary>
		public int LoginRoleId
		{
			get
			{
				int result = 0;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					string data = identity.FindFirst(ClaimTypes.Role)?.Value;
					if (data.Split(",").Length >= 1)
						int.TryParse(data.Split(",")[0], out result);
				}

				return result;
			}
		}

		#endregion

		#region string LoginRoleName 登录用户角色名称。

		/// <summary>
		/// 登录用户角色名称。
		/// </summary>
		public string LoginRoleName
		{
			get
			{
				string result = string.Empty;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					string data = identity.FindFirst(ClaimTypes.Role)?.Value;
					if (data.Split(",").Length >= 2)
						result = data.Split(",")[1];
				}

				return result;
			}
		}

		#endregion

		#region string LoginPhone 登录用户手机号。

		/// <summary>
		/// 登录用户手机号。
		/// </summary>
		public string LoginPhone
		{
			get
			{
				string result = string.Empty;

				string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
				if (!string.IsNullOrWhiteSpace(token))
				{
					System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
					ClaimsPrincipal principal = tokenHandler.ValidateToken(token, ValidationParameters, out SecurityToken securityToken);

					ClaimsIdentity identity = principal?.Identity as ClaimsIdentity;
					result = identity.FindFirst(ClaimTypes.MobilePhone)?.Value;
				}

				return result;
			}
		}

		#endregion

		//public Model.DB.Identity.Users LoginUserId
		//{
		//    get
		//    {
		//        Model.DB.Identity.Users result = null;

		//        string token = HttpContext.Request.Headers.ContainsKey("Token") ? HttpContext.Request.Headers["Token"].ToString() : "";
		//        if (!string.IsNullOrWhiteSpace(token))
		//        {
		//            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
		//            System.IdentityModel.Tokens.Jwt.JwtSecurityToken securityToken = tokenHandler.ReadJwtToken(token);
		//            System.IdentityModel.Tokens.Jwt.JwtPayload data = securityToken.Payload;

		//            string json = data.ContainsKey("UserInfo") ? data["UserInfo"].ToString() : "";
		//            if (!string.IsNullOrWhiteSpace(json))
		//                result = TomNet.Json.JsonHelper.FromJson<Model.DB.Identity.Users>(json);
		//        }

		//        return result;
		//    }
		//}
	}
}
